// 小队
const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const squadCollection = db.collection('squad')
const TcbRouter = require('tcb-router');

// 云函数入口函数
exports.main = async (event, context) => {
	let app = new TcbRouter({event})
	const {OPENID} = cloud.getWXContext()
	// 创建小队
	app.router('save',async (ctx,next)=>{
		// member 小队成员 Array 
		// captain 队长信息 Object  名称和id 和 队长头像
		let {name,member,captain} = event;
		captain.openid = OPENID
		ctx.body = squadCollection.add({
			data: {
				name,
				member,
				captain,
				openid: OPENID,
				createTime: Date.now()
			}
		})
	})
	// 小队列表
	app.router('list',async (ctx,next)=>{
		let {pageNum=1,pageSize=1000} = event;
		ctx.body = await squadCollection
			.skip((pageNum-1)*pageSize)
			.limit(pageSize)
			.orderBy('createTime','desc')
			.get()
			.then(res=>res);
	})
	// 小队详情
	app.router('detail',async (ctx,next)=>{
		let {id} = event;
		id = id.trim()
		ctx.body = await squadCollection
			.where({
				_id: id
			})
			.get()
			.then(res=>res.data[0]);
	})
	// 获取当前用户的小队
	app.router('getOPenidList',async (ctx,next)=>{
		let {pageNum=1,pageSize=1000} = event;
		const _ = db.command
		ctx.body = await squadCollection
			.where(_.or([{
				member: _.all([
					_.elemMatch({
						openid: OPENID
					})
				])
			},
			{
				captain:{
					openid: OPENID
				}
			}
		]))
			.skip((pageNum-1)*pageSize)
			.limit(pageSize)
			.orderBy('createTime','desc')
			.get()
			.then(res=>res);
	})
	// 添加小队成员
	app.router('addcaptain',async (ctx,next)=>{
		let {id,user} = event;
		id = id.trim()
		user.openid = OPENID
		let squad = await squadCollection
			.where({
				_id: id
			}).get()
		if(squad.data.length>0){
			let q = squad.data[0].member.filter(item=>{
				return item.openid === OPENID
			})
			if(q.length>0){
				ctx.body = {
					msg: '您已加入当前团队'
				}
				return
			}
		}
		ctx.body = await squadCollection
			.where({
				_id: id
			})
			.update({
				data: {
					member: [
						...squad.data[0].member,
						user
					]
				},
			})
			.then(res=>res);
	})
	return app.serve()
}